package com.bum.guru.dj.service.helper;

import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

import com.bum.guru.dj.dao.SongDAO;
import com.bum.guru.exp.dj.om.Song;
import com.bum.guru.util.BaseParser;

public class LoadSongHelper implements ApplicationContextAware {
	private SongDAO	songDAO;

	@Override
	public void setApplicationContext(ApplicationContext arg0) throws BeansException {
		Executors.newScheduledThreadPool(1).scheduleWithFixedDelay(new Runnable() {
			@Override
			public void run() {
				try {
					loadSongs();
				} catch (Throwable e) {
					e.printStackTrace();
				}
			}
		}, 30, 7200, TimeUnit.SECONDS);
	}

	public void loadSongs() throws Exception {
		int failCount = 0;
		List<Song> songs = songDAO.list(0, 0, 1);

		long startId = songs.get(0).getId();
		while (failCount < 10) {
			if (!load(++startId)) {
				++failCount;
			}
		}
	}

	public boolean load(long id) {
		String url = "http://matxac.com/Play/1/" + id + ".xml";
		System.out.println(id);
		String html = BaseParser.loadHtml(url);
		String name = BaseParser.parseContent(html, "<Title>", "</Title>");
		String track = BaseParser.parseContent(html, "<location>", "</location>");

		if (StringUtils.isNotBlank(name) && StringUtils.isNotBlank(track)) {
			try {
				System.out.println(id + " " + name + " " + track);
				songDAO.add(id, name, track);
			} catch (Exception e) {
				e.printStackTrace();
			}
			return true;
		}
		return false;
	}

	public void setSongDAO(SongDAO songDAO) {
		this.songDAO = songDAO;
	}

}
